import { createRouter, createWebHashHistory } from 'vue-router'
import Layout from '../views/layout/index.vue'
import Home from '@/views/home/index.vue'
import useStore from '@/store'
const router = createRouter({
  history: createWebHashHistory(),
  // 切换路由时 页面滚动到最顶部
  scrollBehavior: () => {
    return {
      top: 0,
    }
  },
  routes: [
    {
      path: '/',
      component: Layout,
      children: [
        { path: '', component: Home },
        {
          path: '/category/:id',
          component: () => import('@/views/catagory/index.vue'),
        },
        {
          path: '/category/sub/:id',
          component: () => import('@/views/catagory/sub.vue'),
        },
        {
          path: '/goods/:id',
          component: () => import('@/views/goods/index.vue'),
        },
        {
          path: '/cart',
          component: () => import('@/views/cart/index.vue'),
        },
        {
          path: '/member/checkout',
          component: () => import('@/views/member/pay/checkout.vue'),
        },
      ],
    },
    { path: '/login', component: () => import('@/views/Login/index.vue') },
    {
      path: '/login/callback',
      component: () => import('@/views/login/callback.vue'),
    },
  ],
})

// 配置路由导航守卫，拦截 /member开头的所有的地址
router.beforeEach((to, from, next) => {
  const { cart } = useStore()
  // 情况1： 已登录 直接放行
  if (cart.isLogin) {
    return next()
  }
  // 情况2：没有登录---但路径中包含member
  if (!cart.isLogin) {
    if (to.path.includes('/member')) {
      next({
        path: '/login',
        query: {
          redirectUrl: to.fullPath,
        },
      })
    } else {
      next()
    }
  }
})
export default router
